const database = require("../../database/index");
const dayjs = require("dayjs");

// 添加轮播图
exports.add = (req, res) => {
    const sql = "insert into carousel set ?";
    const created = dayjs().format("YYYY-MM-DD HH:mm:ss");
    database.query(
        sql,
        {
            ...req.body,
            created
        },
        function (err, results) {
            if (err) return res.response(err);
            res.response("添加成功", 0);
        }
    );
};

// 删除轮播图
exports.delete = (req, res) => {
    const { id } = req.body;
    const sql = "delete from carousel where id=?";
    database.query(sql, id, (err) => {
        if (err) return res.response(err);
        res.response("删除成功", 0);
    });
};

// 修改轮播图
exports.edit = (req, res) => {
    const { id } = req.body;
    let sql = "update carousel set ? where id=?";
    const updated = dayjs().format("YYYY-MM-DD HH:mm:ss");
    database.query(sql, [{ ...req.body, updated }, id], (err) => {
        if (err) return res.response(err);
        res.response("修改成功", 0);
    });
};

// 查询轮播图
exports.list = (req, res) => {
    const { content, page, pageSize } = req.body;
    let sql = "select * from carousel";
    let countSql = "select count(*) as total from carousel";
    let params = [];
    if (content) {
        sql += sql.includes("where") ? " and (remark like?)" : " where (remark like?)";
        countSql += countSql.includes("where") ? " and (remark like?)" : " where (remark like?)";
        params.push(`%${content}%`)
    };
    database.query(countSql, params, function (countErr, countResult) {
        if (countErr) return res.response(countErr);
        const total = countResult[0] ? countResult[0].total : 0;
        if (page && pageSize) {
            const offset = (page - 1) * pageSize;
            sql += " LIMIT ? OFFSET ?";
            params.push(Number(pageSize), offset);
        }
        database.query(sql, params, function (err, result) {
            if (err) return res.response(err);
            return res.send({
                code: 0,
                message: "查询成功",
                total,
                result,
            });
        });
    });
};

